//
//  TMDeviceInfo.swift
//  TMBD Movie App
//
//  Created by zhangkai on 2023/4/22.
//

import UIKit
import CoreTelephony
import AdSupport
import UIKit
//import JavaScriptCore

enum ConfigKey:String {
    case proType = "proType"
    case proDeadLine = "proDeadLine"     //vip 到期时间
    case first_Install = "first_Install"
    case storeReviewTime = "storeReviewTime" //零点
    case loginType = "loginType" //初始版本，解锁版本
  
}

@objcMembers
class TMDeviceInfo: NSObject {
    static var _device: UIDevice = {
        let dev = UIDevice.current
        return dev
    }()
    
    class var model:String{
        var systemInfo = utsname()
        uname(&systemInfo)
        let platform = withUnsafePointer(to: &systemInfo.machine.0) { ptr in
            return String(cString: ptr)
        }
        return platform
    }
    class var brand:String{
        return _device.model
    }
    class var device:String{
        return _device.systemName
    }
    class var systemName:String{
        return _device.name
    }
    
    class var systemVersion:String{
        return _device.systemVersion
    }
    class var idfa:String{
        return ASIdentifierManager.shared().advertisingIdentifier.uuidString
    }
    
    class var deviceNo:String{
        if UserDefaults.standard.string(forKey: "DEVICENO") == nil {
            let deviceNo = UUID().uuidString
            UserDefaults.standard.setValue(deviceNo, forKey: "DEVICENO")
            UserDefaults.standard.synchronize()
        }
        return UserDefaults.standard.string(forKey: "DEVICENO")!
    }
    
    class var devicereg_id:String{
        return UserDefaults.standard.string(forKey: "FCMID") ?? ""
    }
    
    class var installTime:String{
        let time = "\(ConfigFile.getIntValueFromConfigWith(key: .first_Install))"
        return "\(time)"
    }

    class var currentLang:String{
        return NSLocale.preferredLanguages.first!
        
    }
    class var countrycode:String{
        return Locale.current.regionCode!
    }

    class var timezone:String{
        let zone = TimeZone.current.abbreviation()!
        let zoneStr = zone as NSString
    
        return  zoneStr.substring(from: zone.count - 1)
    }
    class var isPad:Bool{
        return _device.userInterfaceIdiom == .pad
    }
    
    class var simcard:String{
        let networkInfo = CTTelephonyNetworkInfo()
        let ctDict = networkInfo.serviceSubscriberCellularProviders!
        
        var count = 0
        for key in ctDict.keys {
            let carrier1 = ctDict[key]
            if (carrier1?.mobileCountryCode?.count ?? 0) > 0{
                count += 1
            }
        }
        return "\(count)"
        
    }
    
    class var imsi:String{
       
        let nums = ["52501","52502","52503","310010","310200","310210","310220","310170","50501","24101","20404","23410","23415","23433","23430"]
        var num = UserDefaults.standard.object(forKey: "device_imsiKey")
        if num == nil {
            let i:Int = Int(arc4random() % 14)
            num = nums[i]
            UserDefaults.standard.setValue(num, forKey: "device_imsiKey")
        }
        return num as! String
    }
    
    
    class var apns_id:String{
       
        var num = UserDefaults.standard.object(forKey: "apns_id")
        if num == nil {
            let letters = "abcdefghijklmnopqrstuvwxyz0123456789"
            num =  String((0 ..< 64).map{ _ in letters.randomElement()! })
            UserDefaults.standard.setValue(num, forKey: "apns_id")
        }
        return num as! String
    }
    
    class var app_id:String{
       
//        if (appInfoModel.app_id.count) > 0 {
//            return appInfoModel.app_id
//        }
        return "265"
    }
    
    class var app_ver:String{
       
//        if (appInfoModel.app_ver.count) > 0 {
//            return appInfoModel.app_ver
//        }
        return "1.2.0"
    }
    
    class var country:String{
       
//        if (appInfoModel.country.count) > 0 {
//            return appInfoModel.country
//        }
        return "US"
    }
    
    class var installGitTime:String{
       
//        if (appInfoModel.installTime.count) > 0 {
//            let githubDate = Date(timeIntervalSince1970: Double(appInfoModel.installTime)!)
//            let localDate = Date(timeIntervalSince1970: Double(self.installTime)!)
//            if githubDate > localDate {
//                ConfigFile.setIntValueToConfigWith(key: .first_Install, intValue: GetTimestamp(nil))
//                return "\(GetTimestamp(nil))"
//
//            }else{
//                return self.installTime
//            }
//        }
        return self.installTime
    }
    
    class var prefer:String{
       
//        if (appInfoModel.prefer.count) > 0 {
//            return appInfoModel.prefer
//        }
        return ""
    }
    
    class var r1:String{
       
//        if (appInfoModel.r1.count) > 0 {
//            return appInfoModel.r1
//        }
        return "100"
    }
    
    class var stageflag:String{
       
//        if (appInfoModel.stageflag.count) > 0 {
//            return appInfoModel.stageflag
//        }
        return "3"
    }
    
    class var token:String{
       
//        if (appInfoModel.token.count) > 0 {
//            return appInfoModel.token
//        }
        return "1"
    }
    
    class var uid:String{
       
//        if (appInfoModel.uid.count) > 0 {
//            return appInfoModel.uid
//        }
        return "0"
    }
    
    class var tmversion:String{
       
//        if (appInfoModel.version.count) > 0 {
//            return appInfoModel.version
//        }
        return "4.0"
    }
    
    class var vp:String{
       
//        if (appInfoModel.vp.count) > 0 {
//            return appInfoModel.vp
//        }
        return "0"
    }
        
}


@objcMembers
class ConfigFile: NSObject {
    
    class func databasePath()->String{
        
        
        let libPath = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true).first! as NSString
        
//
        
        return libPath.appendingPathComponent( "/PM_Config.dat")
    }
    
    //MARK: Object
    class func setOjectToConfigWith(key:ConfigKey,value:String){

        let finaPath = databasePath()
        var writeDict = NSMutableDictionary(contentsOfFile: finaPath)
        if writeDict == nil {
            writeDict = NSMutableDictionary(capacity: 1)
        }
        if writeDict == nil {
            return
        }
        writeDict?.setObject(value, forKey: key.rawValue as NSCopying)
        let bv = writeToFileWith(writeDict: writeDict!, filePath: finaPath)

        if bv {
            
        }
    }
    class func getValueFromConfigWith(key:ConfigKey)->String{
        let finaPath = databasePath()
        var ret = ""
        let readDict = NSMutableDictionary(contentsOfFile: finaPath)
        if readDict == nil {
            return ""
        }else{
            ret = readDict?.object(forKey: key.rawValue) as? String ?? ""
        }

        return ret
    }

    //MARK: Int
    class func setIntValueToConfigWith(key:ConfigKey,intValue:Int){
        
        let finaPath = databasePath()
        var writeDict = NSMutableDictionary(contentsOfFile: finaPath)
        if writeDict == nil {
            writeDict = NSMutableDictionary(capacity: 1)
        }
        if writeDict == nil {
            return
        }
        let num1 = NSNumber(value:intValue)
        writeDict?.setObject(num1, forKey: key.rawValue as NSCopying)
        let bv = writeToFileWith(writeDict: writeDict!, filePath: finaPath)

        if bv {
            
        }

    }
    
    class func getIntValueFromConfigWith(key:ConfigKey)->Int{
        let finaPath = databasePath()
        var ret =  0
        let readDict = NSMutableDictionary(contentsOfFile: finaPath)
        if readDict == nil {
            return 0
        }else{
            let num1 = readDict?.object(forKey: key.rawValue) as? NSNumber
            ret = num1?.intValue ?? 0
        }
        return ret
    }

    //MARK: Int
    class func setBoolValueToConfigWith(key:ConfigKey,boolValue:Bool){

        if boolValue {
            setIntValueToConfigWith(key: key, intValue: 1)
        }else{
            setIntValueToConfigWith(key: key, intValue: 0)
        }

    }
    class func getBoolValueFromConfigWith(key:ConfigKey)->Bool{
        let valueC = getIntValueFromConfigWith(key: key)
        return valueC == 1
    }

    class func clearConfigFile(){
        let finaPath = databasePath()
        let nullDict = NSMutableDictionary(contentsOfFile: finaPath)
        nullDict?.removeAllObjects()
        let _ = writeToFileWith(writeDict: nullDict!, filePath: finaPath)

    }

    private class func writeToFileWith(writeDict:NSMutableDictionary,filePath:String)->Bool{
        objc_sync_enter(self)
        let writeFlag = writeDict.write(toFile: filePath, atomically: true)
        objc_sync_exit(self)
        return writeFlag


    }
}


let requestParame:[String:String] = [
    "apns_id":TMDeviceInfo.apns_id,
    "app_id":TMDeviceInfo.app_id,
    "app_ver":TMDeviceInfo.app_ver,
    "brand":TMDeviceInfo.brand,
    "country":TMDeviceInfo.country,
    "device":TMDeviceInfo.device,
    "deviceNo":TMDeviceInfo.deviceNo,
    "idfa":TMDeviceInfo.idfa,
    "imsi":TMDeviceInfo.imsi,
    "installTime":TMDeviceInfo.installTime,
    "lang":TMDeviceInfo.currentLang,
    "model":TMDeviceInfo.model,
    "os_ver":TMDeviceInfo.systemVersion,
    "prefer":TMDeviceInfo.prefer,
    "r1":TMDeviceInfo.r1,
    "resolution":String(format: "%0.fx%0.f", UIScreen.main.currentMode!.size.width,UIScreen.main.currentMode!.size.height),
    "simcard":TMDeviceInfo.simcard,
    "stageflag":TMDeviceInfo.stageflag,
    "timezone":TMDeviceInfo.timezone,
    "token":TMDeviceInfo.token,
    "uid":TMDeviceInfo.uid,
    "version":TMDeviceInfo.tmversion,
    "vp":TMDeviceInfo.vp]
